<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    v-model="visible"
    title="检查项详情"
    @cancel="visible = false"
    @confirm="visible = false"
  >
    <div class="detail-content">
      <el-row :gutter="20">
        <template v-for="(value, key) in filteredData" :key="key">
          <el-col :span="24" v-if="key !== 'inspectionQuestion'">
            <div class="detail-item">
              <span class="label">{{ formatLabel(key) }}：</span>
              <span class="value">
                <!-- 添加检查结果和处理方式的映射显示 -->
                <template v-if="key === 'inspectionResult'">
                  <el-tag
                    :type="getInspectionResultColor(value)"
                    size="large"
                    effect="plain"
                  >
                    {{ getInspectionResultText(value) }}
                  </el-tag>
                </template>
                <template v-else-if="key === 'dealType'">
                  <el-tag
                    :type="getDealTypeColor(value)"
                    size="large"
                    effect="plain"
                  >
                    {{ getDealTypeText(value) }}
                  </el-tag>
                </template>
                <template v-else>
                  {{ value || '无' }}
                </template>
              </span>
            </div>
          </el-col>
          <el-col :span="24" v-else>
            <div class="detail-item">
              <span class="label">{{ formatLabel(key) }}：</span>
              <div class="editor-container">
                <Editor
                  class="editor"
                  :model-value="decodeBase64(value) || '无'"
                  :defaultConfig="viewEditorConfig"
                  mode="default"
                  @onCreated="handleEditorCreated"
                />
              </div>
            </div>
          </el-col>
        </template>
      </el-row>
    </div>
  </v-dialog>
</template>

<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { ref, computed, shallowRef, onBeforeUnmount } from "vue";
import { InspectionCheckDTO } from "@/api/airport/inspection/inspectionCheck";
import { Editor } from "@wangeditor/editor-for-vue";
import { ElRow, ElCol, ElTag } from "element-plus";
import '@wangeditor/editor/dist/css/style.css'

interface Props {
  modelValue: boolean;
  row: InspectionCheckDTO;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

// 添加：Base64解码函数
const decodeBase64 = (base64Str: string): string => {
  if (!base64Str) return '';
  try {
    // 先解码Base64，再处理UTF-8编码
    return decodeURIComponent(escape(window.atob(base64Str)));
  } catch (error) {
    console.error('Base64解码失败:', error);
    return '';
  }
};

// 定义检查结果对应的颜色映射
const inspectionResultColorMap = {
  '1': 'success',
  '2': 'danger',
  '3': 'info'
};

// 定义检查结果的文本映射
const inspectionResultTextMap = {
  '0': '未开始',
  '1': '检查通过',
  '2': '不通过',
  '3': '不适用'
};

// 定义处理方式的映射关系
const dealTypeMap = {
  '0': '检查通过',
  '1': '直接整改',
  '2': '建模后整改'
};

// 定义处理方式对应的颜色映射
const dealTypeColorMap = {
  '0': 'success',
  '1': 'warning',
  '2': 'danger'
};

// 获取检查结果文本
const getInspectionResultText = (value: string) => {
  return inspectionResultTextMap[value] || value || '未知';
};

// 获取检查结果颜色
const getInspectionResultColor = (value: string) => {
  return inspectionResultColorMap[value] || 'info';
};

// 获取处理方式文本
const getDealTypeText = (value: string) => {
  return dealTypeMap[value] || value || '未知';
};

// 获取处理方式颜色
const getDealTypeColor = (value: string) => {
  return dealTypeColorMap[value] || 'info';
};

// 定义需要展示的字段
const fieldsToShow = [
  "inspectionName",
  "checkContent",
  "inspectionUserName",
  "checkDeptName",
  "inspectedDeptName",
  "inspectionResult",
  "dealType",
  "dutyDeptName",
  "curDealDeptName",
  "baseCycle",
  "checkDepartments",
  "checkMethod",
  "checkOpinion",
  "checkSign",
  "checkStandardCode",
  "checkTermCode",
  "companyBasis",
  "companyClause",
  "correctMeasure",
  "correctMeasureDeadlineTime",
  "correctMeasureDealPeople",
  "correctMeasureDealTime",
  "correctMeasureResult",
  "createTime",
  "startTime",
  "dealResult",
  "directCause",
  "endTime",
  "feedback",
  "fundamentalCause",
  "inspectionDeadlineTime",
  "inspectionDeptName",
  "tittle",
  "inspectionQuestion",
  "integrationSource",
  "lawsBasis",
  "lawsClause",
  "preventionMeasure",
  "preventionMeasureDeadlineTime",
  "preventionMeasureDealPeople",
  "preventionMeasureDealTime",
  "preventionMeasureResult",
  "professional",
  "rectificationRequire",
  "relationType",
  "remark",
  "selfcheckId",
  "checkStandard",
  "complianceCriteria",
  "determinationStandard",
];

// 过滤出需要展示且有值的字段
const filteredData = computed(() => {
  const data: Record<string, any> = {};
  const showDealType = props.row.inspectionResult !== '0'; // 当检查结果不为'未开始'时才显示处理方式

  fieldsToShow.forEach((field) => {
    // 如果检查结果为'未开始'，则不显示处理方式
    if (field === 'dealType' && !showDealType) {
      return;
    }

    if (props.row[field] !== undefined && props.row[field] !== null) {
      data[field] = props.row[field];
    }
  });
  return data;
});

// 格式化字段标签
const formatLabel = (key: string) => {
  const labelMap: Record<string, string> = {
    checkContent: "检查内容",
    checkDepartments: "检查部门",
    baseCycle: "基础周期",
    checkMethod: "检查方式",
    checkOpinion: "检查意见",
    checkSign: "检查签字",
    checkStandardCode: "检查标准编码",
    checkTermCode: "检查项编码",
    companyBasis: "公司依据",
    companyClause: "公司条款",
    complianceCriteria: "符合性判定标准",
    checkStandard: "检查标准",
    correctMeasure: "纠正措施",
    correctMeasureDeadlineTime: "纠正措施截止时间",
    correctMeasureDealPeople: "纠正措施处理人",
    correctMeasureDealTime: "纠正措施处理时间",
    correctMeasureResult: "纠正措施结果",
    createTime: "检查项目创建时间",
    dealResult: "处理结果",
    dealType: "处理方式",
    determinationStandard: "判定标准",
    directCause: "直接原因",
    endTime: "结束时间",
    feedback: "反馈",
    fundamentalCause: "根本原因",
    inspectionDeadlineTime: "检查截止时间",
    inspectionDeptName: "检查部门名称",
    inspectionId: "检查计划 ID",
    inspectionName: "检查计划名称",
    tittle:"存在问题",
    inspectionQuestion: "问题详情",
    inspectionResult: "检查结果",
    inspectionUserId: "检查人 ID",
    inspectionUserName: "检查人",
    integrationSource: "融合来源",
    lawsBasis: "法律法规依据",
    lawsClause: "法律法规条款",
    preventionMeasure: "预防措施",
    preventionMeasureDeadlineTime: "预防措施截止时间",
    preventionMeasureDealPeople: "预防措施处理人",
    preventionMeasureDealTime: "预防措施处理时间",
    preventionMeasureResult: "预防措施结果",
    professional: "专业",
    rectificationRequire: "整改要求",
    relationType: "关联类型",
    remark: "备注",
    selfcheckId: "自查事项 ID",
    startTime: "检查开始时间",
    updateTime: "更新时间",
    dutyDeptName: '责任部门名称',
    curDealDeptName: '当前处理部门名称',
    checkDeptName:'检查部门',
    inspectedDeptName:'检查对象',
  };
  return labelMap[key] || key;
};

// Editor相关配置
const viewEditorRef = shallowRef();
const viewEditorConfig = { readOnly: true }; // 配置为只读模式

const handleEditorCreated = (editor) => {
  viewEditorRef.value = editor;
};

// 组件销毁时，同时销毁编辑器
onBeforeUnmount(() => {
  const editor = viewEditorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped>
.detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.label {
  width: 200px;
  font-weight: bold;
  flex-shrink: 0;
}

.value {
  flex: 1;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 70%;
}

.editor {
  height: auto;
  min-height: 150px;
  width: 100%;
}
</style>
